<template>
	<view>
		<u-popup :show="show"  mode="bottom" :closeable="true" :round="10" @close="close">
		   <view class="popDialog">
			   
		      <view class="font-32 text-bold title" v-if="!pageType">预约活动</view>
			  <view class="font-32 text-bold title" v-else>填写信息</view>

			  <!-- <scroll-view class="scrollH" scroll-y> -->

		      <view class="boxPanel flex-between" >
		        <view class="text-bold flex-y-center">
					联系人
					<text class="font-24 c-89">（必填项）</text>
				</view>
		        <input type="text" placeholder="请输入联系人" v-model="name" placeholder-class="inputs" class="text-right" style="width: 50%;">
		      </view>
			  
			  <view class="boxPanel flex-between">
			    <view class="text-bold flex-y-center" >联系电话
					<text class="font-24 c-89">（必填项）</text>
				</view>
			    <input type="number" maxlength="11" placeholder="请输入联系电话" v-model="mobile" placeholder-class="inputs" class="text-right" style="width: 50%;">
			  </view>

			  <view class="boxPanel flex-between" @click="openTimePicker" v-if="!moduleType">
			    <view class="text-bold">预约时间</view>
				<view class="flex-y-center" style="width: 58%;justify-content: flex-end;">
			    	<input type="text"  disabled placeholder="请选择时间" v-model="subscribe_time" placeholder-class="inputs" class="text-right" style="width: 100%;">
					<u-icon name="arrow-right" color="#788096" size="14"></u-icon>
				</view>
			  </view>

			  <view class="boxPanel flex-between">
				<view class="text-bold">购买数量</view>
				<view class="flex-y-center" style="width: 58%;justify-content: flex-end;">
			    	<u-number-box v-model="goods_num" @change="valChange"></u-number-box>
				</view>
			  </view>

			  <view class="boxPanel flex-between"  v-if="moduleType == 'social'">
			    <view class="text-bold">报名人数</view>
				<view class="flex-y-center" style="width: 50%;">
			    	<input type="number" maxlength="2"  placeholder="请填写人数" v-model="people_num" placeholder-class="inputs" class="text-right">
				</view>
			  </view>

			  <view class="boxPanel flex-x-between" @click="chooseAddress()" v-if="!moduleType">
			    <view class="text-bold" >服务地址</view>
				<view class="flex-y-center" style="width: 50%;">
					<input type="text"   placeholder="请选择地址" v-model="address" disabled placeholder-class="inputs" class="text-right" v-if="!address">
					<view class="inputs" style="line-height: 1.4;color:#172140" v-else>{{address}}</view>
					<u-icon name="arrow-right" color="#788096" size="14"></u-icon>
				</view>
			  </view>
			  
			  <view class="boxPanel flex-between">
			    <view class="text-bold flex-y-center">
					备注
			  	</view>
			    <input type="text"  placeholder="请填写备注" v-model="remark" placeholder-class="inputs" class="text-right" style="width: 50%;">
			  </view>

			  <view class="boxPanel">
					<view class="font-30 text-bold m-b-20">
						支付方式
					</view>
					<view class="payrow" v-for="(item,index) in paylist" :key="index" @click="changePayment(index)">
						<image :src="$util.img(item.icon)" mode="" class="payimg"></image>
						{{item.name}}
						<text class="color-title2 m-l-20" v-if="item.name == '余额支付'">可用¥{{balance}}</text>
						<image :src="$util.img('image/radio2.png')" mode="" class="radio" v-if="payIndex == index"></image>
						<image :src="$util.img('image/radio.png')" mode="" class="radio" v-else></image>
					</view>
			  </view>

			<!-- </scroll-view> -->
			  
			  <view style="height: 120rpx;"></view>
		      <view class="footer fixfooter" v-if="parseFloat(price) == 0">
		      	<view class="submit" @click="submit">{{!pageType?'立即预约':'立即购买'}}</view>
		      </view>
			  
			  <view class="footer2 fixfooter" v-else>
			    <view class="">
			  	<view class="font-24 c-8d">共 1 件 需支付</view>
			  	<view class="money c-origin text-bold font-52 flex" style="align-items: baseline;margin-top: -16rpx;">
			  	  <text class="font-28 c-origin">￥</text>{{memberPrice}}
			  	</view>
			    </view>
			    <view class="submit" @click="submit">立即支付</view>
			  </view>
			  
		   </view>
		 </u-popup>

		 <!-- 引入日历 -->
		<u-calendar :show="showCalendar" color="#ff8f33" :round="round" rowHeight="46" @confirm="confirmCalendar"></u-calendar>
		<!-- 引入时分弹窗 -->
		<!-- <u-datetime-picker ref="datetimePicker" :show="showTime" :formatter="formatter" @cancel="showTime = false" @confirm="confirmTime" title="选择时间" v-model="value1" mode="time" confirmColor="#ff8f33"></u-datetime-picker> -->
		<!-- 引入时间组件 -->
		<choose-time ref="chooseTime" :show="showTime" @close="showTime = false" @chooseTime="chooseTime"></choose-time>
	</view>
</template>

<script>
	import chooseTime from 'components/chooseTime/chooseTime.vue';
	export default {
		name:"sign",
		props: {
		  show: {
		    type: Boolean,
		    default: false
		  },
		  price: {
		    type: Number,
		    default: 0
		  },
		  goodsid: {
		    type: Number,
		    default: 0
		  },
		  pageType: {
		    type: String,
		    default: ''
		  },
		  moduleType: {
			type: String,
			default: '',   //模块类型social 文娱社交
		  },
		  backUrl: {
			type: String,
			default: ''
		  },
		  memberPrice: {
			type: Number,
			default: 0
		  },
		},
		components: {
			chooseTime
		},
		data() {
			return {
				name: '',
				mobile: '',
				subscribe_time: '',
				address: '',

				isSubmitting: false,
				defaultList: [],
				//日历数据
				showCalendar: false,
				round: 10,
				date: '',
				// 时分数据
				showTime: false,
				value1: '00:00',
				remark: '',
				people_num: '',
				minDate: '',
				// 支付参数
				paylist: [{
				  name: '微信支付',
				  icon: '/image/pay2.png'
				},{
				  name: '余额支付',
				  icon: '/image/pay1.png'
				}],
				payIndex: 0,
				balance: 0,  //余额
				is_balance: 0, //是否余额支付
				goods_num: 1, //商品数量


			};
		},
		created() {
			// 初始化时间往后推迟一个小时的时间戳
			// this.minDate = new Date().getTime() + 3600 * 1000;
			// console.log(this.minDate);

			// 获取缓存subscribe_order，如果有数据就进行赋值
			if(uni.getStorageSync('subscribe_order')) {
				var data = uni.getStorageSync('subscribe_order');
				this.name = data.subscribe_name;
				this.mobile = data.subscribe_mobile;
				this.address = data.subscribe_address;
				this.subscribe_time = data.subscribe_time;
			}else {
				// 获取缓存的用户信息，将昵称赋值给姓名，手机号赋值
				var userInfo = uni.getStorageSync('userInfo');
				if(userInfo) {
					this.name = userInfo.nickname;
					this.mobile = userInfo.mobile;
				}
			}
			if(uni.getStorageSync('userInfo')) {
				this.balance = uni.getStorageSync('userInfo').balance;
			}
			this.getDefaultAddress();
		},
		methods: {
			chooseTime(e) {
				this.subscribe_time = e.time_day;
				this.showTime = false;
			},
			changePayment(index) {
				if(index == 1) {
					// 比对余额是否满足支付金额
					if(parseFloat(this.balance) < parseFloat(this.memberPrice)) {
						uni.showToast({
							title: '余额不足，请选择其他支付方式',
							icon: 'none'
						})
						return;
					}else {
						this.is_balance = 1;
						this.payIndex = index;
					}
				}else {
					this.is_balance = 0;
					this.payIndex = index;
				}
				this.$forceUpdate();
			},
			chooseAddress() {
				this.$util.redirectTo('/pages/address/address',{back: this.backUrl});
			},
			openTimePicker() {
				this.showTime = true;
			},
			formatter(type, value) {
                if (type === 'hour') {
                    return `${value}时`
                }
                if (type === 'minute') {
                    return `${value}分`
                }
                return value
            },
			confirmTime(e) {
				console.log(e)
				let selectedTimeStr = this.date + ' ' + e.value + ':00'
      
				// 将选择的时间转换为时间戳
				let selectedTime = new Date(selectedTimeStr).getTime()
				// 获取当前时间往后推迟一个小时的时间戳
				let minTime = new Date().getTime() + 3600 * 1000
				
				// 判断选择的时间是否小于最小允许时间
				if (selectedTime < minTime) {
					uni.showToast({
					title: '预约时间必须至少在当前时间1小时后',
					icon: 'none'
					})
					return false
				}

				this.showTime = false;
				this.subscribe_time = this.date + ' ' + e.value;
			},
			confirmCalendar(e) {
				console.log(e);
				this.date = e[0];
				this.showCalendar = false;
				this.showTime = true;
			},
			getDefaultAddress() {
				this.$api.sendRequest({
					url: "/api/memberaddress/page",
						data: {
						page: 1,
						page_size: 30,
					},
					success: (res) => {
						if (res.code == 0) {
							var arr = res.data.list;
							var newDefault = [];
							arr.forEach((v, k) => {
							if (v.is_default == 1) {
								newDefault.push(v);
								arr.splice(k, 1);
							}
							});
							let defaultList = newDefault;
							this.address = defaultList[0].full_address + defaultList[0].address;


						}
					},
				});
			},
			close() {
				this.$emit("close")
			},
			submit() {
				if(!this.name) {
					uni.showToast({
						title: '请输入姓名',
						icon: "none"
					})
					return false;
				}
				if(!this.mobile || this.mobile.length != 11) {
					uni.showToast({
						title: '请输入手机号',
						icon: "none"
					})
					return false;
				}

				// 增加时间校验逻辑
				if(!this.moduleType&&this.subscribe_time) {

					// 第一种时间格式如: 2025-08-26 10:00进行的比较形式
					// let selectedTimeStr = this.subscribe_time + ':00'
      
					// // 将选择的时间转换为时间戳
					// let selectedTime = new Date(selectedTimeStr).getTime()
					// // 获取当前时间往后推迟一个小时的时间戳
					// let minTime = new Date().getTime() + 3600 * 1000

					// 判断选择的时间是否小于最小允许时间
					// if (selectedTime < minTime) {
					// 	uni.showToast({
					// 	title: '预约时间必须至少在当前时间1小时后',
					// 	icon: 'none'
					// 	})
					// 	return false
					// }

					// 第二种时间格式如: 2025-08-26 10:00-12:00进行的比较形式
					// 解析预约时间段
					const datePart = this.subscribe_time.split(' ')[0];
					const timePart = this.subscribe_time.split(' ')[1].split('-')[0];
					const appointmentTimeStr = `${datePart} ${timePart}:00`;
					
					const appointmentTime = new Date(appointmentTimeStr).getTime();
					const minTime = new Date().getTime() + 3600 * 1000;

					// console.log(datePart, timePart,appointmentTimeStr,appointmentTime);

					if (appointmentTime < minTime) {
						uni.showToast({
							title: '预约时间必须至少在当前时间1小时后',
							icon: 'none'
						})
						return false;
					}
					
				}

				if(this.isSubmitting) return false;
				this.isSubmitting = true;

				this.$api.sendRequest({
			      url: "/api/subscribeordercreate/create",
			      data: {
			        goods_id: this.goodsid,
					name: this.name,
					mobile: this.mobile,
					subscribe_time: this.subscribe_time,
					address: this.address,
					remark: this.remark,
					people_num: this.people_num,
					is_balance: this.is_balance,

			      },
			      success: res => {
					// 将数据存入缓存中
					uni.setStorageSync('subscribe_order', {
						subscribe_time: this.subscribe_time,
						subscribe_address: this.address,
						subscribe_name: this.name,
						subscribe_mobile: this.mobile,
					});
			        if(res.code == 0) {
			          if(parseFloat(this.price) == 0 || this.is_balance == 1) {
			            uni.showToast({
			              title: '预约成功',
			              icon: "none"
			            })
			            setTimeout(() => {
			              this.$emit("close");
						  uni.reLaunch({
								url: '/otherpages/yuOrder/yuOrderList'
							});
			            }, 1500)
			          }else{
			            this.$emit("close");
			            this.pay(res.data);
			          }
			        }else {
						this.$util.showToast(res.message);
					}
			      }
			    })
			},
		 	pay(out_trade_no) {
				this.$api.sendRequest({
					url: '/api/pay/pay',
					data: {
						out_trade_no: out_trade_no,
						pay_type: "wechatpay"
					},
					success: res => {
						if (res.code >= 0) {
							var payData = res.data.data;
							uni.requestPayment({
								provider: 'wxpay',
								timeStamp: payData.timeStamp,
								nonceStr: payData.nonceStr,
								package: payData.package,
								signType: payData.signType,
								paySign: payData.paySign,
								success: res => {
									this.$util.showToast({ title: '支付成功' });
									// 重新加载用户信息接口，更新用户信息数据
									this.getMemberInfo();
									uni.reLaunch({
										url: '/otherpages/yuOrder/yuOrderList'
									});
								},
								fail: res => {
									this.flag = false;
									if (res.errMsg == 'requestPayment:fail cancel') {
										this.$util.showToast({ title: '您已取消支付' });
									} else {
										uni.showModal({ content: '支付失败,失败原因: ' + res.errMsg, showCancel: false });
									}
									
								}
							});
						} else {
							this.$util.showToast({
								title: '未获取到支付信息！'
							});
						}
					}
				});
			},
			getMemberInfo() {
				this.$api.sendRequest({
					url: "/api/member/info",
					data: {},
					success: res => {
						if (res.code >= 0 && res.data) {
							uni.setStorageSync('userInfo', res.data);
						}
					},
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
.scrollH {
	height: 60vh;
	overflow-y: auto;
}
.popDialog {
  width: 100%;
  padding: 40rpx 0;
  border-radius: 20rpx 20rpx 0 0;
  box-sizing: border-box;
  background: $color-bg;
  .title {
    text-align: center;
    padding-bottom: 38rpx;
  }
  .boxPanel {
    .inputs {
      font-size: 28rpx;
      color: #B5B9C7;
    }
    .txt {
      font-size: 32rpx;
      font-weight: bold;
    }
  }
}

// 支付方式选项
.payrow {
	display: flex;
	align-items: center;
	padding: 16rpx 0;
	font-size: 26rpx;
	width: 100%;
	.payimg {
		width: 67rpx;
		height: 67rpx;
		margin-right: 20rpx;
	}
	.radio {
		width: 34rpx;
		height: 34rpx;
		margin-left: auto;
	}
}

.footer2 {
	 display: flex;
	 justify-content: space-between;
	 align-items: center;
	 padding: 0 24rpx;
	 box-sizing: border-box;
	 .submit {
	   width: 265rpx;
	   height: 86rpx;
	   line-height: 86rpx;
	   text-align: center;
	   background-color: $color-title2;
	   color: #fff;
	   border-radius: 40rpx;
	 }
}
</style>